<script setup>
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'
	import datasetApi from '@/views/plugin/dashboard/api/datasetApi'
	import { message } from 'ant-design-vue'
	import { nextTick, ref, watch } from 'vue'
	import { SyncOutlined, FilterOutlined, SaveOutlined } from '@ant-design/icons-vue'
	import QueryConditions from '@/views/plugin/dashboard/view/data/components/dataset/queryConditions.vue'
	import ColumnSelector from '@/views/plugin/dashboard/view/data/components/dataset/columnSelector.vue'
	import FormatConfig from '@/views/plugin/dashboard/view/data/components/dataset/formatConfig.vue'
	import ConfigPreview from '@/views/plugin/dashboard/view/data/components/dataset/configPreview.vue'
	import { useSimpleQueryStore } from '@/views/plugin/dashboard/store/simpleQuery'

	const store = useSimpleQueryStore()

	// 数据表列表
	const tableList = ref([])
	// 查询结果
	const queryResult = ref([])
	// 加载状态
	const loading = ref(false)

	// 打开表单并初始化数据
	const onOpen = (record) => {
		if (record) {
			store.setFormData(record)
			nextTick(() => {
				loadTables().then(() => {
					if (store.formData.itemConfig.tableName) {
						// 加载表字段信息并执行初始查询
						dataConnectorApi
							.metadata({
								id: store.formData.dataConnectorId,
								tableName: store.formData.itemConfig.tableName
							})
							.then((res) => {
								store.setColumns(
									res.columns.map((column) => ({
										title: `${column.name}${column.comment ? ` (${column.comment})` : ''}`,
										dataIndex: column.name.toLowerCase(),
										key: column.name,
										width: 180,
										ellipsis: true
									}))
								)
								store.setSelectedColumns(store.formData.itemConfig.columns.map((col) => col.key) || [])
								// 执行初始查询
								executeQuery()
							})
					}
				})
			})
		}
	}

	// 执行查询
	const executeQuery = async () => {
		if (!store.formData.itemConfig.tableName) {
			message.warning('请先选择数据表')
			return
		}
		// 校验查询条件
		const hasInvalidCondition = store.formData.config?.conditions.some((condition) => {
			// 所有条件都需要字段名
			if (!condition.field) {
				return true
			}

			// 空值判断类操作符，只需要有字段名
			if (['is_null', 'is_not_null', 'is_empty', 'is_not_empty'].includes(condition.operator)) {
				return false
			}

			// 范围判断类操作符，需要至少有一个值
			if (['between', 'not_between'].includes(condition.operator)) {
				if (!Array.isArray(condition.value)) {
					condition.value = []
				}
				return !condition.value[0] && !condition.value[1]
			}

			// 其他所有操作符都需要有值
			return !condition.value
		})

		if (hasInvalidCondition) {
			message.warning('请完善查询条件')
			return
		}
		try {
			loading.value = true
			const res = await datasetApi.preview(store.formData)
			queryResult.value = res || []
		} catch (error) {
			console.error('查询失败:', error)
		} finally {
			loading.value = false
			console.log(store.$state)
		}
	}

	// 获取数据表列表
	const loadTables = async () => {
		try {
			tableList.value = await dataConnectorApi.tables({ id: store.formData.dataConnectorId })
		} catch (error) {
			console.error('获取数据表列表失败:', error)
		}
	}

	// 获取数据集配置
	const getConfig = () => {
		if (!store.formData.itemConfig.tableName) {
			return null
		}
		return {
			tableName: store.formData.itemConfig.tableName,
			fields: store.formData.itemConfig.selectedColumns,
			conditions: store.formData.config?.conditions
		}
	}

	defineExpose({
		onOpen,
		getConfig
	})

	const emit = defineEmits(['loadData', 'onSave'])
	const key = 'loadingTable'

	// 监听表名变化
	watch(
		() => store.formData.itemConfig.tableName,
		async (newValue) => {
			if (newValue) {
				try {
					message.loading({ content: '加载中', key, duration: 0 })
					const res = await dataConnectorApi.metadata({
						id: store.formData.dataConnectorId,
						tableName: newValue
					})
					store.setColumns(
						res.columns.map((column) => ({
							title: `${column.name}${column.comment ? ` (${column.comment})` : ''}`,
							dataIndex: column.name.toLowerCase(),
							key: column.name,
							width: 180,
							ellipsis: true
						}))
					)
					store.setSelectedColumns(store.formData.itemConfig.columns.map((col) => col.key) || [])
					// 清空之前的结果
					queryResult.value = []
					// 清空之前的条件
					store.formData.config.conditions = []
					// 执行一次查询
					executeQuery()
					message.destroy()
				} catch (error) {
					console.error('获取表字段失败:', error)
					message.error('获取表字段失败')
				}
			}
		}
	)

	// 筛选模式状态
	const filterMode = ref(false)

	// 切换筛选模式
	const toggleFilterMode = () => {
		filterMode.value = !filterMode.value
		if (!filterMode.value) {
			// 关闭筛选模式时执行查询
			executeQuery()
		}
	}
	const fieldList = ref([])
</script>

<template>
	<div class="query-container">
		<!-- 顶部操作区 -->
		<div class="flex items-center gap-4 mb-4">
			<a-select
				v-model:value="store.formData.itemConfig.tableName"
				placeholder="请选择数据表"
				class="w-60"
				:options="tableList.map((table) => ({ value: table, label: table }))"
			/>
			<div class="flex items-center gap-2">
				<a-tooltip title="刷新数据">
					<a-button type="link" :loading="loading" @click="executeQuery">
						<template #icon><sync-outlined /></template>
					</a-button>
				</a-tooltip>
				<a-tooltip title="筛选 & 排序">
					<a-button
						type="link"
						:class="{ 'text-primary bg-primary-1 shadow-sm': filterMode }"
						@click="toggleFilterMode"
					>
						<template #icon><filter-outlined /></template>
					</a-button>
				</a-tooltip>
				<column-selector />
				<format-config />
				<config-preview />
				<a-tooltip title="保存配置">
					<a-button type="primary" @click="emit('onSave')">
						<template #icon><save-outlined /></template>
						保存
					</a-button>
				</a-tooltip>
			</div>
		</div>

		<!-- 查询条件区 -->
		<query-conditions
			v-show="filterMode"
			:conditions="store.formData.itemConfig.formData?.config.conditions"
			:field-list="fieldList"
			:table-name="store.formData.itemConfig.tableName"
			@refreshFun="executeQuery"
		/>

		<!-- 结果集表格区域 -->
		<div class="table-wrapper">
			<!-- 表格容器 -->
			<div class="table-container">
				<a-table
					border
					:columns="store.getTableColumns"
					:dataSource="queryResult"
					:loading="loading"
					:scroll="{ x: 'max-content' }"
					size="small"
					:pagination="{ pageSize: 15 }"
				>
					<template #bodyCell="{ column, text }">
						<template
							v-if="
								store.formData.itemConfig.formatConfig?.some((c) => c.field === column.key && c.type !== 'fieldname')
							"
						>
							{{
								store.applyFormat(
									text,
									store.formData.itemConfig.formatConfig?.find((c) => c.field === column.key)
								)
							}}
						</template>
						<template v-else>
							{{ text }}
						</template>
					</template>
				</a-table>
			</div>
		</div>
	</div>
</template>

<style scoped>
	.query-container {
		padding: 16px;
	}
	.table-wrapper {
		display: flex;
		gap: 16px;
		margin-top: 16px;
	}

	.table-container {
		flex: 1;
		overflow-x: auto;
	}
	:deep(.ant-table-thead > tr > th) {
		white-space: nowrap;
		font-size: 12px;
		padding: 8px 16px;
	}

	.text-primary {
		color: #1890ff;
	}

	.bg-primary-1 {
		background-color: rgba(24, 144, 255, 0.1);
	}
</style>
